<template>
  <div class="app-container  bg-gray">
    <el-card>
      <el-row>
        <div class="header">系统信息</div>
      </el-row>
      <el-row v-for="(item,index) in info" :key="index">
        <el-col :sm="8" :md="7" :lg="6" :xl="4">{{ item['con_name'] }}</el-col>
        <el-col :sm="16" :md="17" :lg="18" :xl="20">{{ item['con_value'] }}
          <el-button v-if="index===0&&$store.getters.id===1" type="text" @click="getHasUpdate">检查更新</el-button>
          <el-button v-if="index===0&&hasUpdate&&$store.getters.id===1" type="text" @click="getHasUpdate">（有新版本, 点击更新）
          </el-button>
          <el-button v-if="index===1&&$store.getters.id===1" type="text" @click="checkWxAppUpdate">检查更新</el-button>
          <router-link to="/wxApp/publishWxApp">
            <el-button v-if="index===1&&hasWxAppUpdate&&$store.getters.id===1" type="text">（有新版本, 点击更新）
            </el-button>
          </router-link>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="site-box margin-top-20">
      <el-row>
        <div class="header">服务器脚本  <el-link href="http://wiki.netbcloud.com/web/#/1?page_id=28" target="_blank">（脚本启动修复方法）</el-link></div>
      </el-row>
      <el-row v-for="(item,index) in scriptData" :key="index">
        <el-col :sm="8" :md="7" :lg="6" :xl="4">{{ item['name'] }}</el-col>
        <el-col :sm="16" :md="17" :lg="18" :xl="20" :style="{'color': item.status===1?'rgb(30, 194, 160)': 'red'}">{{ item['statusText'] }}
        <span style="color: #b7b7b7;"> | 最近运行时间: {{ item.execTime }}</span></el-col>
      </el-row>
    </el-card>

    <el-dialog :visible.sync="updateDialogVisible" :modal-append-to-body="false" title="系统更新说明" width="1080px">
      <div v-html="newVersion['remarks']">{{ newVersion['remarks']||'暂无更新内容说明' }}</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible=false">以 后 更 新</el-button>
        <el-button type="primary" @click="doUpdate">确 定 更 新</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="updateProgressVisible"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      title="更新中..."
      width="520px">
      <el-progress :text-inside="true" :stroke-width="26" :percentage="updateProgress"/>
      <div class="progress-status">{{ updateProgressStatus + '...' }}</div>
      <div class="progress-value">{{ updateProgressValue }}</div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="updateProgress===100" type="primary" @click="refresh">立即刷新</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { $config } from 'vue-element-simple';
export default {
  data() {
    return {
      // 是否有更新
      hasUpdate: false,
      // 小程序是否有更新
      hasWxAppUpdate: false,
      // 新版本内容
      newVersion: {
        url: '',
        version_number: '',
        remarks: ''
      },
      // 更新内容弹窗
      updateDialogVisible: false,
      // 更新进度弹窗
      updateProgressVisible: false,
      // 更新进度
      updateProgress: 0,
      // 更新内容
      updateProgressValue: '',
      // 更新状态
      updateProgressStatus: '检查更新文件',

      info: '',
      // 脚本信息: '',
      scriptData: []
    }
  },
  watch: {
  },
  created() {
    this.getData();
    this.checkWxAppUpdate();
    this.getScriptData();
  },
  methods: {
    // 获取信息
    getData() {
      const url = 'configs/index';
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.info = res.data;
        if (this.$store.getters.id === 1 && $config['ENV'] === 'LOCAL') {
          this.checkUpdate();
        }
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员');
      });
    },

    // 获取脚本信息
    getScriptData() {
      const url = 'index/getJavaScriptStatus';
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.scriptData = res.data;
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员');
      })
    },

    // 主动检查更新
    getHasUpdate(){
      if ($config['ENV'] === 'LOCAL') {
        this.$store.dispatch('SetIsUpdate', true)
        this.checkUpdate()
      }
    },
    // 检查系统是否有更新
    checkUpdate() {
      const url = 'check';
      this.$store.dispatch('GetConnect', { url }).then(res => {
          if (res.status === 1) {
            this.hasUpdate = true;
            if (this.$store.getters.isUpdate) {
              this.$confirm('CRM系统有新发布版本，是否查看更新说明并更新?', '更新', {
                confirmButtonText: '查看更新',
                cancelButtonText: '以后更新',
                type: 'warning'
              }).then(() => {
                this.updateDialogVisible = true;
                this.newVersion = res.data;
              }).catch(() => {
                this.$store.dispatch('SetIsUpdate', false);
                this.$alert('可通过系统设置-->站点信息中进行更新', '提示', { confirmButtonText: '确定' });
              });
            }
          } else {
            this.$message.success(res.msg);
          }
        }
      ).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员');
      })
    },

    // 关闭站点
    async stopWebSite() {
      const url = 'settingOutdated';
      const stopWebsite = await this.$store.dispatch('GetConnect', { url });
      console.log('=========关闭站点=========');
      console.log(stopWebsite);
      if (stopWebsite['code'] !== 0) {
        this.$message.error('关闭站点失败~')
      }
    },

    // 执行更新系统
    async doUpdate() {
      // 是否开启了停站功能
      if (this.queryMatch(204)) {
        this.stopWebSite()
      }
      this.updateProgressVisible = true;

      // 获取更新包文件列表
      let reDownLoadTime = 0;
      let url = 'readyDownload';
      let updatePackageFileList = null;
      // 根据更新包数遍历获取文件列表
      this.updateProgressStatus = '检查更新包...';
      for (let i = 1; i <= this.newVersion['number']; i++) {
        const data = {
          url: this.newVersion['url'],
          number: i
        };
        this.updateProgressValue = '检查更新包-->' + i;
        this.updateProgress = parseFloat((this.updateProgress + (15 / this.newVersion['number'])).toFixed(2));
        console.log('检查更新包-->' + i);
        updatePackageFileList = await this.$store.dispatch('GetConnect', { url, data });
        console.log(await updatePackageFileList);
        // 后端说下载失败要重新调用
        if (updatePackageFileList.data && updatePackageFileList.data.result === 1) {
          reDownLoadTime++;
          if (reDownLoadTime === 3) {
            this.$message.error('更新失败,更新包异常,请联系管理员')
            this.updateProgressStatus = '更新失败...'
            this.updateProgressValue = updatePackageFileList['msg']
            this.updateProgress = 100
            return;
          }
          i = 0;
          this.updateProgress = 0;
        }
      }
      console.log('=========更新包文件名列表=========');
      console.log(updatePackageFileList);

      // 遍历文件列表解压文件
      url = 'readyUnzip';
      this.updateProgressStatus = '解压更新文件...';
      for (let i = 0; i < updatePackageFileList.data.length; i++) {
        const data = {
          file_name: updatePackageFileList.data[i]
        };
        this.updateProgressValue = updatePackageFileList.data[i];
        this.updateProgress = parseFloat((this.updateProgress + (50 / updatePackageFileList.data.length)).toFixed(2));
        console.log('=========解压文件-->' + i);
        await this.$store.dispatch('GetConnect', { url, data });
      }

      // 获取解压完成的文件目录列表
      url = 'getDirName';
      const updateFileDirList = await this.$store.dispatch('GetConnect', { url });
      console.log('=========更新文件夹目录列表=========');
      console.log(updateFileDirList);

      // 更新结果
      let updateResult = null;

      // 执行覆盖更新操作
      url = 'moveDir';
      this.updateProgressStatus = '覆盖更新文件...';
      for (let i = 0; i < updateFileDirList.data.length; i++) {
        const data = {
          dirName: updateFileDirList.data[i]
        };
        updateResult = await this.$store.dispatch('GetConnect', { url, data });
        console.log('=========覆盖更新文件夹-->' + i);
        this.updateProgressValue = updateFileDirList.data[i];
        this.updateProgress = parseFloat((this.updateProgress + (10 / updateFileDirList.data.length)).toFixed(2));
      }

      console.log('=========覆盖更新完成=========');
      console.log(updateResult);

      // 获取数据库目录列表
      url = 'getDbTableNames';
      const backupDBList = await this.$store.dispatch('GetConnect', { url });
      console.log('=========获取数据库目录列表=========');
      console.log(backupDBList);

      // 执行备份数据库操作
      url = 'backupsTableName';
      const timeBeforeTotal = new Date().getTime();
      this.updateProgressStatus = '备份数据库数据...';
      for (let i = 0; i < backupDBList.data.length; i++) {
        for (let j = 0; j < backupDBList.data[i]['number']; j++) {
          const data = {
            table: backupDBList.data[i]['table'],
            number: j + 1
          }
          const timeBefore = new Date().getTime();
          updateResult = await this.$store.dispatch('GetConnect', { url, data });
          const timeAfter = new Date().getTime();
          console.log('=========备份数据库数据' + (i + 1) + '-->' + backupDBList.data[i]['table'] + '-->' + (j + 1) + '-->耗时: ' + (timeAfter - timeBefore));
          this.updateProgressStatus = '备份数据库数据(' + i + '/' + backupDBList.data.length + ')...';
          this.updateProgressValue = backupDBList.data[i]['table'] + '-->' + (j + 1);
          this.updateProgress = parseFloat((this.updateProgress + ((20 / backupDBList.data.length) / backupDBList.data[i]['number'])).toFixed(2));
        }
      }

      console.log('=========备份数据库数据完成=========');
      this.updateProgress = parseFloat((this.updateProgress + 20).toFixed(2));
      const timeAfterTotal = new Date().getTime();
      console.log('总耗时: ' + (timeAfterTotal - timeBeforeTotal) / 1000);
      console.log(updateResult);

      // 执行数据库更新
      url = 'updateDatabase';
      this.updateProgressStatus = '更新数据库文件...';
      updateResult = await this.$store.dispatch('GetConnect', { url });
      this.updateProgressValue = '更新中...';
      this.updateProgress = parseFloat((this.updateProgress + 5).toFixed(2));

      console.log('=========更新数据库文件完成=========');
      console.log(updateResult);

      if (updateResult['code'] === 0) {
        this.updateProgressStatus = '已完成...';
        this.updateProgressValue = '';
        this.updateProgress = 100;
      } else {
        // loading.close()
        this.updateProgressStatus = '更新失败...';
        this.updateProgressValue = updateResult['msg'];
        this.updateProgress = 100;
      }
    },
    // 刷新页面
    refresh() {
      this.$router.go(0);
    },

    // 检查小程序是否有新版本
    checkWxAppUpdate() {
      // const url = 'wxMini/checkUpdate';
      const url = 'wxMiniPublish/checkUpdate';
      const data = { projectName: '微购儿CRM' };
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
          if (res.status) {
            this.hasWxAppUpdate = true;
            this.$confirm('小程序有新发布版本，是否查看更新说明并发布?', res.data.title, {
              confirmButtonText: '查看更新',
              cancelButtonText: '以后更新',
              type: 'warning'
            }).then(() => {
              this.$router.push({
                path: '/wxApp/publishWxApp'
              })
            }).catch(() => {
              this.$alert('可通过小程序设置-->发布小程序中进行更新', '提示', { confirmButtonText: '确定' });
            })
          }
        }
      ).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员');
      })
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../styles/index.scss';
.el-row {
  .header {
    padding: 6px 20px;
    font-size: 14px;
    font-weight: 600;
    background-color: $gray;
  }
  border: 1px solid $gray;
  border-bottom: none;
  &:last-child {
    border-bottom: 1px solid $gray;
  }
  .el-col {
    padding: 2px 20px;
    font-size: 11px;
    &:last-child {
      border-left: 1px solid $gray;
    }
    .el-button{
      padding: 0 12px;
      font-size: 11px;
    }
  }
}
.progress-status{
  padding: 20px 0;
}

.el-card__body {
  padding: 10px;
}
</style>
